package com.sywb.chuangyebao.library.player;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import com.alivc.player.AliyunErrorCode;
import com.aliyun.vodplayer.media.AliyunLocalSource;
import com.aliyun.vodplayer.media.AliyunVodPlayer;
import com.aliyun.vodplayer.media.IAliyunVodPlayer;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.sywb.chuangyebao.library.R;
import com.sywb.chuangyebao.library.player.listener.OnPlayerListener;

import org.bining.footstone.log.Logger;
import org.bining.footstone.utils.ApkUtils;
import org.bining.footstone.utils.FileUtils;
import org.bining.footstone.utils.NetUtils;
import org.bining.footstone.utils.ScreenUtils;
import org.bining.footstone.utils.ToastUtils;

import java.lang.ref.WeakReference;

/**
 * 阿里云播放
 * https://help.aliyun.com/document_detail/61918.html?spm=5176.doc61915.2.5.zXk3c0#h2-aliyunvodplayer1
 */
public class AliPlayerView extends FrameLayout implements IVideoController, View.OnClickListener, SeekBar.OnSeekBarChangeListener {

    private FrameLayout llContainer;

    private ImageView ivPreview;

    private LinearLayout llPlayer;
    private ImageView ivPlayer;

    public TextView tvDuration;

    public TextView tvReset;

    public LinearLayout llShare;
    public TextView tvShareWechat;
    public TextView tvShareFriend;
    public TextView tvShareQQ;
    public TextView tvShareSpace;

    public LinearLayout llErrorView;
    public TextView tvErrorMsg;
    public TextView tvErrorBtn;

    private LinearLayout llLoading;

    private LinearLayout llTools;
    private TextView tvCurrentPosition;
    private SeekBar sbProgress;
    private TextView tvTotalDuration;
    private ImageView ivFullScreen;

    private ProgressBar pbProgress;

    private Context mContext;

    private AliyunVodPlayer aliyunVodPlayer = null;
    private AliyunLocalSource mLocalSource = null;

    private int mPlayMode;//视频模式 MODE_VIDEO:点播 MODE_LIVE:直播
    private boolean isCanReplay;// 记录视频播放完成后是否可以重播
    private boolean isCanShare = true;// 记录视频播放完成后是否可以分享
    private boolean mAutoPlayerState = false;//记录由系统触发AutoPause时播放器是否在播放

    private OnPlayerListener onPlayerListener;

    private CountDownTimer mCountDownTimer;

    private Handler progressUpdateTimer;

    /**
     * 启动工具栏显示倒计时（默认五秒）
     *
     * @param time 时间（毫秒）
     */
    private void startCountDown(int time) {
        stopCountDown();
        mCountDownTimer = new CountDownTimer(time, 1000) {
            @Override
            public void onTick(long l) {
            }

            @Override
            public void onFinish() {
                hideToolsView();
            }
        };
        mCountDownTimer.start();
    }

    private void stopCountDown() {
        if (mCountDownTimer != null) {
            mCountDownTimer.onFinish();
            mCountDownTimer.cancel();
            mCountDownTimer = null;
        }
    }

    @SuppressLint("HandlerLeak")
    private void startUpdateTimer() {
        stopUpdateTimer();
        if (progressUpdateTimer == null) {
            progressUpdateTimer = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    if (getPlayerState() == AliyunVodPlayer.PlayerState.Started || getPlayerState() == AliyunVodPlayer.PlayerState.Replay) {
                        int curPosition = (int) aliyunVodPlayer.getCurrentPosition();
                        int bufferPosition = aliyunVodPlayer.getBufferingPosition();
                        int duration = (int) aliyunVodPlayer.getDuration();
                        updateProgress(curPosition, bufferPosition, duration);
                    }
                    startUpdateTimer();
                }
            };
        }
        progressUpdateTimer.sendEmptyMessageDelayed(0, 100);
    }

    private void stopUpdateTimer() {
        if (progressUpdateTimer != null) {
            progressUpdateTimer.removeMessages(0);
        }
    }

    public AliPlayerView(Context context) {
        this(context, null);
    }

    public AliPlayerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    @SuppressLint("WrongConstant")
    public AliPlayerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        inflate(context, R.layout.layout_video_player, this);

        mContext = context;

        this.llContainer = findViewById(R.id.ll_container);
        this.ivPreview = findViewById(R.id.iv_preview);

        this.llPlayer = findViewById(R.id.ll_player);
        this.ivPlayer = findViewById(R.id.iv_player);

        this.tvDuration = findViewById(R.id.tv_duration);

        this.tvReset = findViewById(R.id.tv_reset);

        this.llShare = findViewById(R.id.ll_share);
        this.tvShareWechat = findViewById(R.id.tv_share_wechat);
        this.tvShareFriend = findViewById(R.id.tv_share_friend);
        this.tvShareQQ = findViewById(R.id.tv_share_qq);
        this.tvShareSpace = findViewById(R.id.tv_share_space);

        this.llErrorView = findViewById(R.id.ll_error_view);
        this.tvErrorMsg = findViewById(R.id.tv_error_msg);
        this.tvErrorBtn = findViewById(R.id.tv_error_btn);

        this.llLoading = findViewById(R.id.ll_loading);

        this.llTools = findViewById(R.id.ll_tools);
        this.tvCurrentPosition = findViewById(R.id.tv_current_position);
        this.sbProgress = findViewById(R.id.sb_progress);
        this.tvTotalDuration = findViewById(R.id.tv_total_duration);
        this.ivFullScreen = findViewById(R.id.iv_full_screen);

        this.pbProgress = findViewById(R.id.pb_progress);

        llContainer.setOnClickListener(this);
        ivPlayer.setOnClickListener(this);
        tvReset.setOnClickListener(this);
        tvShareWechat.setOnClickListener(this);
        tvShareFriend.setOnClickListener(this);
        tvShareQQ.setOnClickListener(this);
        tvShareSpace.setOnClickListener(this);
        tvErrorBtn.setOnClickListener(this);
        ivFullScreen.setOnClickListener(this);
        sbProgress.setOnSeekBarChangeListener(this);

        changeContainerViewSize(((Activity) mContext).getRequestedOrientation() == Configuration.ORIENTATION_LANDSCAPE);

        initVodPlayer();
    }

    /**
     * 初始化播放器
     */
    private void initVodPlayer() {
        aliyunVodPlayer = new AliyunVodPlayer(mContext);
        aliyunVodPlayer.setPlayingCache(true, FileUtils.getAppSdPath(FileUtils.PATH_VIDEO), 60 * 60 /*时长, s */, 1024 /*大小，MB*/);
        aliyunVodPlayer.setAutoPlay(false);
        aliyunVodPlayer.disableNativeLog();

        aliyunVodPlayer.setOnPreparedListener(new MyPrepareListener(this));
        aliyunVodPlayer.setOnFirstFrameStartListener(new MyFirstFrameListener(this));
        aliyunVodPlayer.setOnErrorListener(new MyErrorListener(this));
        aliyunVodPlayer.setOnCompletionListener(new MyCompletionListener(this));
        aliyunVodPlayer.setOnSeekCompleteListener(new MySeekCompleteListener(this));
        aliyunVodPlayer.setOnStoppedListner(new MyStoppedListener(this));
        aliyunVodPlayer.setOnLoadingListener(new MyLoadingListener(this));
        aliyunVodPlayer.setOnBufferingUpdateListener(new MyBufferingUpdateListener(this));
        aliyunVodPlayer.setOnInfoListener(new MyInfoListener());
        aliyunVodPlayer.setOnVideoSizeChangedListener(new MyVideoSizeChangedListener());
        aliyunVodPlayer.setOnChangeQualityListener(new MyChangeQualityListener());
        aliyunVodPlayer.setOnRePlayListener(new MyRePlayListener());
        aliyunVodPlayer.setOnCircleStartListener(new MyCircleStartListener());
        aliyunVodPlayer.setOnAutoPlayListener(new MyAutoPlayListener());

        SurfaceView rsvPlayer = new SurfaceView(mContext);
        rsvPlayer.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                if (aliyunVodPlayer != null) {
                    aliyunVodPlayer.setDisplay(holder);
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                if (aliyunVodPlayer != null) {
                    aliyunVodPlayer.surfaceChanged();
                }
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
            }
        });
        aliyunVodPlayer.setDisplay(rsvPlayer.getHolder());

        if (llContainer.getChildCount() > 0) {
            llContainer.removeAllViews();
        }

        llContainer.addView(rsvPlayer, new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }

    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.ll_container) {// 视频容器被点击,若当前在播放则显示播放器工具栏
            if (getPlayerState() == IAliyunVodPlayer.PlayerState.Started) {
                showToolsView();
            }
        } else if (i == R.id.iv_player) {// 播放按钮被点击,若当前是停止状态则播放视频，在播放则暂停
            if (getPlayerState() == IAliyunVodPlayer.PlayerState.Started) {
                pause();
            } else if (getPlayerState() == IAliyunVodPlayer.PlayerState.Paused) {
                resume();
            } else {
                start();
            }
        } else if (i == R.id.tv_error_btn) {
            int sceneCode = (int) tvErrorBtn.getTag();
            switch (sceneCode) {
                case 3:
                    if (!NetUtils.isConnected()) {
                        ApkUtils.openNetSetting(mContext);
                    } else {
                        isCanReplay = true;
                        start();
                    }
                    break;
                case 4:
                    PlayerUtils.setUseTrafficPlay(true);
                    if (getPlayerState() == IAliyunVodPlayer.PlayerState.Paused) {
                        resume();
                    } else {
                        start();
                    }
                    break;
                default:
                    isCanReplay = true;
                    start();
                    break;
            }
        } else if (i == R.id.tv_reset) {
            isCanReplay = true;
            start();
        } else if (i == R.id.tv_share_wechat) {
            if (onPlayerListener != null) {
                onPlayerListener.onShare(1);
            }
        } else if (i == R.id.tv_share_friend) {
            if (onPlayerListener != null) {
                onPlayerListener.onShare(2);
            }
        } else if (i == R.id.tv_share_qq) {
            if (onPlayerListener != null) {
                onPlayerListener.onShare(3);
            }
        } else if (i == R.id.tv_share_space) {
            if (onPlayerListener != null) {
                onPlayerListener.onShare(4);
            }
        } else if (i == R.id.iv_full_screen) {// 全屏按钮被点击,放大到全屏
            if (onPlayerListener != null) {
                onPlayerListener.onClickScreenDirection();
            }
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
        // SeekBar进度改变
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // SeekBar开始拖动
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        // SeekBar停止拖动
        seekTo(seekBar.getProgress());
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        changeContainerViewSize(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE);
    }

    /**
     * 根据屏幕方向改变视频容器的大小
     */
    public void changeContainerViewSize(boolean screenOrientation) {
        ViewGroup.LayoutParams layoutParams = llContainer.getLayoutParams();
        layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        int screenWidth = ScreenUtils.getScreenWidth();
        if (screenOrientation) {// 横屏
            //隐藏状态栏
            ((Activity) mContext).getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            llContainer.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);

            ivFullScreen.setImageResource(R.drawable.small_screen);
            layoutParams.height = screenWidth;
        } else {// 竖屏
            //显示状态栏
            ((Activity) mContext).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            llContainer.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);

            ivFullScreen.setImageResource(R.drawable.full_screen);
            layoutParams.height = (int) (screenWidth * 0.56F);
        }
        llContainer.setLayoutParams(layoutParams);
    }

    /**
     * 获取播放器对象
     */
    public AliyunVodPlayer getAliyunVodPlayer() {
        return aliyunVodPlayer;
    }

    /**
     * 获取播放器状态
     */
    public IAliyunVodPlayer.PlayerState getPlayerState() {
        if (aliyunVodPlayer == null) {
            initVodPlayer();
            error(2, 2, "播放器异常,请稍后重试");
            return IAliyunVodPlayer.PlayerState.Error;
        } else {
            return aliyunVodPlayer.getPlayerState();
        }
    }

    /**
     * 设置播放监听
     */
    public void setOnPlayerListener(OnPlayerListener onPlayerListener) {
        this.onPlayerListener = onPlayerListener;
    }

    /**
     * 解注册播放监听
     */
    public void unOnPlayerListener() {
        if (onPlayerListener != null) {
            onPlayerListener = null;
        }
    }

    private void setInitView() {
        stopCountDown();
        stopUpdateTimer();

        ivPlayer.setImageResource(R.drawable.play_white);

        ivPreview.setVisibility(View.VISIBLE);
        ivPlayer.setVisibility(View.VISIBLE);
        tvDuration.setVisibility(View.VISIBLE);

        llLoading.setVisibility(View.GONE);

        tvReset.setVisibility(View.GONE);
        llShare.setVisibility(View.GONE);

        llErrorView.setVisibility(View.GONE);

        llTools.setVisibility(View.GONE);
        pbProgress.setVisibility(GONE);

        if (onPlayerListener != null) {
            onPlayerListener.onInit();
        }
    }

    private void setLoadingView() {
        stopCountDown();
        stopUpdateTimer();

        ivPlayer.setImageResource(R.drawable.stop_white);

        ivPreview.setVisibility(View.VISIBLE);
        ivPlayer.setVisibility(View.GONE);
        tvDuration.setVisibility(View.GONE);

        llLoading.setVisibility(View.VISIBLE);

        tvReset.setVisibility(View.GONE);
        llShare.setVisibility(View.GONE);

        llErrorView.setVisibility(View.GONE);

        llTools.setVisibility(View.GONE);
        pbProgress.setVisibility(GONE);

        if (onPlayerListener != null) {
            onPlayerListener.onPrepared();
        }
    }

    private void setStartedView() {
        stopCountDown();
        startUpdateTimer();

        ivPlayer.setImageResource(R.drawable.stop_white);

        ivPreview.setVisibility(View.GONE);
        ivPlayer.setVisibility(View.GONE);
        tvDuration.setVisibility(View.GONE);

        llLoading.setVisibility(View.GONE);

        tvReset.setVisibility(View.GONE);
        llShare.setVisibility(View.GONE);

        llErrorView.setVisibility(View.GONE);

        llTools.setVisibility(View.GONE);
        pbProgress.setVisibility(VISIBLE);

        if (onPlayerListener != null) {
            onPlayerListener.onStarted();
        }
    }

    private void setPausedView() {
        stopCountDown();
        stopUpdateTimer();

        ivPlayer.setImageResource(R.drawable.play_white);

        ivPreview.setVisibility(View.VISIBLE);
        ivPlayer.setVisibility(View.VISIBLE);
        tvDuration.setVisibility(View.GONE);

        llLoading.setVisibility(View.GONE);

        tvReset.setVisibility(View.GONE);
        llShare.setVisibility(View.GONE);

        llErrorView.setVisibility(View.GONE);

        llTools.setVisibility(View.VISIBLE);
        pbProgress.setVisibility(GONE);

        if (onPlayerListener != null) {
            onPlayerListener.onPaused();
        }
    }

    private void setCompletedView() {
        stopCountDown();
        stopUpdateTimer();

        ivPlayer.setImageResource(R.drawable.play_white);

        ivPreview.setVisibility(View.VISIBLE);
        ivPlayer.setVisibility(View.GONE);
        tvDuration.setVisibility(View.GONE);

        llLoading.setVisibility(View.GONE);

        tvReset.setVisibility(View.VISIBLE);
        if (isCanShare) {
            llShare.setVisibility(View.VISIBLE);
        }

        llErrorView.setVisibility(View.GONE);

        llTools.setVisibility(View.GONE);
        pbProgress.setVisibility(GONE);

        if (onPlayerListener != null) {
            onPlayerListener.onCompletion();
        }
    }

    private void setErrorView() {
        stopCountDown();
        stopUpdateTimer();

        ivPlayer.setImageResource(R.drawable.play_white);

        ivPreview.setVisibility(View.VISIBLE);
        ivPlayer.setVisibility(View.GONE);
        tvDuration.setVisibility(View.GONE);

        llLoading.setVisibility(View.GONE);

        tvReset.setVisibility(View.GONE);
        llShare.setVisibility(View.GONE);

        llErrorView.setVisibility(View.VISIBLE);

        llTools.setVisibility(View.GONE);
        pbProgress.setVisibility(GONE);
    }

    public void setCanShare(boolean canShare) {
        isCanShare = canShare;
    }

    @Override
    public void init(int playMode) {
        if (aliyunVodPlayer != null && getPlayerState() != IAliyunVodPlayer.PlayerState.Idle) {
            return;
        }

        setInitView();

        this.mPlayMode = playMode;
        switch (playMode) {
            case IVideoController.MODE_VIDEO:
                llPlayer.setVisibility(View.VISIBLE);
                tvCurrentPosition.setVisibility(View.VISIBLE);
                sbProgress.setVisibility(View.VISIBLE);
                tvTotalDuration.setVisibility(View.VISIBLE);

                ivFullScreen.setVisibility(VISIBLE);
                break;
            case IVideoController.MODE_LIVE:
                llPlayer.setVisibility(View.GONE);
                tvCurrentPosition.setVisibility(View.INVISIBLE);
                sbProgress.setVisibility(View.INVISIBLE);
                tvTotalDuration.setVisibility(View.INVISIBLE);

                ivFullScreen.setVisibility(VISIBLE);
                break;
        }
    }

    /**
     * 初始化视频播放器
     *
     * @param playMode    播放模式 0:点播 1:直播
     * @param playUrl     播放地址
     * @param previewPath 预览图地址
     * @param duration    视频总时长
     */
    @Override
    public void init(Activity mActivity, int playMode, String playUrl, String previewPath, String duration) {
        init(playMode);
        initPlayData(mActivity, playUrl, previewPath, duration);
    }

    /**
     * 开始播放
     */
    @Override
    public void start() {
        Logger.e("start getPlayerState():" + getPlayerState());
        if (inspectPlayer()) {
            if (getPlayerState() == IAliyunVodPlayer.PlayerState.Started) {
                setStartedView();
            } else if (getPlayerState() == IAliyunVodPlayer.PlayerState.Completed && !isCanReplay) {
                setCompletedView();
            } else if (getPlayerState() == IAliyunVodPlayer.PlayerState.Paused && mPlayMode == IVideoController.MODE_VIDEO) {
                aliyunVodPlayer.resume();
                setStartedView();
            } else {
                isCanReplay = false;
                aliyunVodPlayer.prepareAsync(mLocalSource);
                setLoadingView();
            }
        }
    }

    @Override
    public void start(Activity mActivity, String playUrl, String previewPath, String duration) {
        initPlayData(mActivity, playUrl, previewPath, duration);
        start();
    }

    private void initPlayData(Activity mActivity, String playUrl, String previewPath, String duration) {
        // if (TextUtils.isEmpty(playUrl)) {
        // playUrl = "http://player.alicdn.com/video/aliyunmedia.mp4";
        // }
        AliyunLocalSource.AliyunLocalSourceBuilder asb = new AliyunLocalSource.AliyunLocalSourceBuilder();
        asb.setSource(playUrl);
        mLocalSource = asb.build();

        Glide.with(mActivity).load(previewPath).apply(new RequestOptions().placeholder(R.drawable.video_def).error(R.drawable.video_def)).into(ivPreview);
        tvDuration.setText(duration);
    }

    /**
     * 暂停播放
     */
    @Override
    public void pause() {
        Logger.e("AliplayerView pause");
        // if (getPlayerState() == IAliyunVodPlayer.PlayerState.Started) {
        if (aliyunVodPlayer == null) {
            return;
        }
        if (mPlayMode == IVideoController.MODE_VIDEO) {
            aliyunVodPlayer.pause();
        } else {
            aliyunVodPlayer.stop();
        }
        // }
        setPausedView();
    }

    /**
     * 自动暂停
     * ps：主页用于系统界面关闭时触发
     */
    @Override
    public void autoPause() {
        Logger.e("AliplayerView autoPause");
        if (getPlayerState() == IAliyunVodPlayer.PlayerState.Started) {
            mAutoPlayerState = true;
            pause();
        }
    }

    /**
     * 恢复播放 必须在调用暂停播放之后调用
     */
    @Override
    public void resume() {
        if (inspectPlayer()) {
            Logger.e("AliplayerView resume " + mPlayMode);
            if (mPlayMode == IVideoController.MODE_VIDEO && getPlayerState() == IAliyunVodPlayer.PlayerState.Paused) {
                aliyunVodPlayer.resume();
                setStartedView();
            } else if (mPlayMode == IVideoController.MODE_LIVE && getPlayerState() == IAliyunVodPlayer.PlayerState.Stopped) {
                isCanReplay = false;
                aliyunVodPlayer.prepareAsync(mLocalSource);
                setLoadingView();
            }
        }
    }

    /**
     * 自动恢复播放
     * ps：主要用于系统界面关闭再打开触发
     */
    @Override
    public void autoResume() {
        if (mAutoPlayerState) {
            Logger.e("AliplayerView autoResume");
            mAutoPlayerState = false;
            resume();
        }
    }

    @Override
    public void stop() {
        if (aliyunVodPlayer != null) {
            Logger.e("AliplayerView stop");
            aliyunVodPlayer.stop();
        }
        setInitView();
    }

    /**
     * 销毁播放器
     */
    @Override
    public void destroy() {
        stop();
        if (aliyunVodPlayer != null) {
            aliyunVodPlayer.release();
            aliyunVodPlayer = null;
        }
        progressUpdateTimer = null;
    }

    /**
     * 指定开始播放位置
     */
    @Override
    public void seekTo(int ms) {
        aliyunVodPlayer.seekTo(ms);
    }

    /**
     * 设置是否可以重新播放
     */
    @Override
    public void setCanReplay(boolean isCanReplay) {
        this.isCanReplay = isCanReplay;
    }

    /**
     * 设置错误相关处理
     *
     * @param causeCode 错误原因码  1:视频地址无效 2:播放器未初始化 3:无网络 4:移动网络
     * @param sceneCode 错误场景码
     * @param message   错误消息内容
     */
    @Override
    public void error(int causeCode, int sceneCode, String message) {
        setErrorView();

        if (onPlayerListener != null) {
            onPlayerListener.onError(causeCode, sceneCode, message);
        }

        tvErrorMsg.setText(message);
        tvErrorBtn.setTag(causeCode);
        tvErrorBtn.setVisibility(View.VISIBLE);
        switch (causeCode) {
            case 1:
                tvErrorBtn.setVisibility(View.INVISIBLE);
                break;
            case 2:
                tvErrorBtn.setVisibility(View.INVISIBLE);
                break;
            case 3:
                tvErrorBtn.setText("联网重试");
                break;
            case 4:
                tvErrorBtn.setText("继续播放");
                break;
//            case 4019:
//                tvErrorBtn.setVisibility(View.INVISIBLE);
//                break;
            default:
                tvErrorMsg.setText("播放器异常,请稍后重试!");
                tvErrorBtn.setText("马上重试");
                aliyunVodPlayer.stop();
                aliyunVodPlayer.release();
                aliyunVodPlayer.prepareAsync(mLocalSource);
                break;
        }

        // 错误原因码
        // ALIVC_ERR_INVALID_PARAM	4001	参数非法，请检查参数
        // ALIVC_ERR_AUTH_EXPIRED	4002	鉴权过期，请重新获取新的鉴权信息
        // ALIVC_ERR_NOTAUTH	4017	播放鉴权失败，请重新获取鉴权信息
        // ALIVC_ERR_INVALID_INPUTFILE	4003	无效的输入，请检查输入地址或者网络链接
        // ALIVC_ERR_MEDIA_UNSUPPORTED	4018	媒体源不支持或者无效
        // ALIVC_ERR_NO_SUPPORT_CODEC	4019	视频编码格式不支持
        // ALIVC_ERROR_NO_INPUTFILE	4004	没有设置视频源或视频地址不存在
        // ALIVC_ERR_READ_DATA_FAILED	4005	读取视频源失败
        // ALIVC_ERR_READ_METADATA_FAILED	4006	读取元数据失败
        // ALIVC_ERR_PLAY_FAILED	4007	播放出错
        // ALIVC_ERROR_LOADING_TIMEOUT	4008	视频加载超时，请检查网络状况
        // ALIVC_ERROR_REQUEST_DATA_ERROR	4009	请求数据错误
        // ALIVC_ERROR_ENCRYPTED_VIDEO_UNSUPORTED	4010	不支持加密视频播放
        // ALIVC_ERROR_VIDEO_FORMAT_UNSUPORTED	4011	视频格式不支持
        // ALIVC_ERROR_PLAYAUTH_PARSE_FAILED	4012	playAuth解析失败
        // ALIVC_ERROR_DECODE_FAILED	4013	视频解码失败
        // ALIVC_ERR_NO_NETWORK	4014	当前网络不可用
        // ALIVC_ERR_MEDIA_ABORTED	4015	获取数据被中止
        // ALIVC_ERR_LOADING_FAILED	4016	网络错误加载视频视频
        // ALIVC_ERR_UNKNOWN	4400	未知错误
        // ALIVC_ERR_REQUEST_ERROR	4500	服务端请求错误
        // ALIVC_ERR_DATA_ERROR	4501	服务器返回数据错误
        // ALIVC_ERR_QEQUEST_SAAS_SERVER_ERROR	4502	请求saas服务器错误
        // ALIVC_ERR_QEQUEST_MTS_SERVER_ERROR	4503	请求mts服务器错误
        // ALIVC_ERR__SERVER_INVALID_PARAM	4504	服务器返回参数无效，请检查参数
        // ALIVC_ERR_ILLEGALSTATUS	4021	非法的播放器状态
        // ALIVC_ERR_NO_VIEW	4022	没有设置显示窗口，请先设置播放视图
        // ALIVC_ERR_NO_MEMORY	4023	内存不足
        // ALIVC_ERR_DOWNLOAD_NO_NETWORK	4101	视频下载时连接不到服务器
        // ALIVC_ERR_DOWNLOAD_NETWORK_TIMEOUT	4102	视频下载时网络超时
        // ALIVC_ERR_DOWNLOAD_QEQUEST_SAAS_SERVER_ERROR	4103	下载请求saas服务器错误
        // ALIVC_ERR_DOWNLOAD_QEQUEST_MTS_SERVER_ERROR	4104	下载请求mts服务器错误
        // ALIVC_ERR_DOWNLOAD_SERVER_INVALID_PARAM	4105	下载服务器返回参数无效，请检查
        // ALIVC_ERR_DOWNLOAD_INVALID_INPUTFILE	4106	视频下载流无效或地址过期
        // ALIVC_ERR_DOWNLOAD_NO_ENCRYPT_FILE	4107	未找到加密文件，请从控制台下载加密文件并集成
        // ALIVC_ERR_DONWNLOAD_GET_KEY	4108	获取秘钥失败，请检查秘钥文件
        // ALIVC_ERR_DOWNLOAD_INVALID_URL	4109	下载地址无效
        // ALIVC_ERR_DONWLOAD_NO_SPACE	4110	磁盘空间不够
        // ALIVC_ERR_DOWNLOAD_INVALID_SAVE_PATH	4111	视频文件保存路径不存在，请重新设置
        // ALIVC_ERR_DOWNLOAD_NO_PERMISSION	4112	当前视频不可下载
        // ALIVC_ERR_DOWNLOAD_MODE_CHANGED	4113	下载模式改变无法继续下载
        // ALIVC_ERR_DOWNLOAD_ALREADY_ADDED	4114	当前视频已经添加到下载项，请避免重复添加
        // ALIVC_ERR_DOWNLOAD_NO_MATCH	4115	未找到合适的下载项，请先添加

        // Error场景码
        // k0PrepareFailed	2	视频准备失败
        // k0OpenFailed	5	文件打开失败
        // k0LoadFailed	8	视频加载失败
        // k0LoadingTimeout	23	视频缓冲超时

    }

    @Override
    public void showToolsView() {
        showToolsView(5000);
    }

    @Override
    public void showToolsView(int time) {
        startCountDown(time);
        ivPlayer.setVisibility(View.VISIBLE);
        llTools.setVisibility(View.VISIBLE);
        pbProgress.setVisibility(View.GONE);
        if (onPlayerListener != null) {
            onPlayerListener.showToolsView();
        }
    }

    @Override
    public void hideToolsView() {
        ivPlayer.setVisibility(View.GONE);
        llTools.setVisibility(View.GONE);
        pbProgress.setVisibility(View.VISIBLE);
        if (onPlayerListener != null) {
            onPlayerListener.hideToolsView();
        }
    }

    @Override
    public void updateProgress(int curPosition, int bufferPosition, int duration) {
        // Logger.d("duration = " + duration + " , bufferPosition = " + bufferPosition + " , curPosition = " + curPosition);

        tvCurrentPosition.setText(PlayerUtils.formatTime(curPosition));
        tvTotalDuration.setText(PlayerUtils.formatTime(duration));

        sbProgress.setMax(duration);
        sbProgress.setSecondaryProgress(bufferPosition);
        sbProgress.setProgress(curPosition);

        pbProgress.setMax(duration);
        pbProgress.setSecondaryProgress(bufferPosition);
        pbProgress.setProgress(curPosition);

        if (onPlayerListener != null) {
            onPlayerListener.updateProgress(curPosition, bufferPosition, duration);
        }
    }

    @Override
    public void changedConfiguration() {
        // 控制方向切换
        int screenOrientation = ((Activity) mContext).getRequestedOrientation();
        if (screenOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            ((Activity) mContext).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            ((Activity) mContext).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }

    /**
     * 检查播放器状态
     */
    @Override
    public boolean inspectPlayer() {
        boolean isCanPlay;
        if (mLocalSource == null) {
            error(1, 1, "当前视频地址无效!");
            isCanPlay = false;
        } else if (aliyunVodPlayer == null) {
            initVodPlayer();
            error(2, 2, "播放器异常,请稍后重试!");
            isCanPlay = false;
        } else {
            if (!NetUtils.isConnected()) {
                if (getPlayerState() == IAliyunVodPlayer.PlayerState.Started) {
                    aliyunVodPlayer.pause();
                }

                if (getPlayerState() != IAliyunVodPlayer.PlayerState.Completed || isCanReplay) {
                    error(3, 3, "网络断开,请联网后重试.");
                }

                // ToastUtils.show(mContext, "当前无网络连接");

                isCanPlay = false;
            } else {
                // 获取当前网络类型
                int netType = NetUtils.getNetworkType();
                // 获取是否可使用移动网络
                boolean useTrafficPlay = PlayerUtils.getUseTrafficPlay();

                Logger.e("netType:" + netType + " useTrafficPlay:" + useTrafficPlay);

                if (netType != 1 && !useTrafficPlay) {
                    if (getPlayerState() == IAliyunVodPlayer.PlayerState.Started) {
                        aliyunVodPlayer.pause();
                    }

                    if (getPlayerState() != IAliyunVodPlayer.PlayerState.Completed || isCanReplay) {
                        error(4, 4, "当前使用数据流量,是否继续播放?");
                    }

                    // ToastUtils.show(mContext, "当前网络连接至数据流量");

                    isCanPlay = false;
                } else {
                    // ivPlayer.setImageResource(R.drawable.play_white);
                    isCanPlay = true;
                }
            }
        }
        return isCanPlay;
    }

    @Override
    public boolean isCanPlayer() {
        return false;
    }

    /**
     * 阿里云播放器准备成功
     */
    private void onPrepared() {
        if (onPlayerListener != null) {
            onPlayerListener.onPrepared();
        }
        aliyunVodPlayer.start();
    }

    /**
     * 阿里云播放器首帧开始播放
     */
    private void onFirstFrameStart() {
        setStartedView();
    }

    /**
     * 阿里云播放器播放错误
     *
     * @param causeCode 错误原因码
     * @param sceneCode 错误场景码
     * @param message   错误消息内容
     */
    private void onError(int causeCode, int sceneCode, String message) {
        if (causeCode == AliyunErrorCode.ALIVC_ERR_INVALID_INPUTFILE.getCode() && !ApkUtils.lacksPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            message = "无本地存储访问权限";
        }
        Logger.e("阿里云播放器播放失败 CauseCode:" + causeCode + " SceneCode:" + sceneCode + " Message:" + message);
        error(causeCode, sceneCode, message);
    }

    /**
     * 阿里云播放器停止播放
     */
    private void onStopped() {
        setPausedView();
    }

    /**
     * 阿里云播放器播放完成
     */
    private void onCompletion() {
        setCompletedView();
    }

    /**
     * 视频开始缓冲
     */
    private void onLoadStart() {// 视频开始缓冲
        llLoading.setVisibility(View.VISIBLE);
    }

    /**
     * 视频缓冲结束
     */
    private void onLoadEnd() {// 视频缓冲结束
        setStartedView();
    }

    /**
     * 视频缓冲进度百分比
     *
     * @param precent 缓冲进度百分比
     */
    private void onLoadProgress(int precent) {
    }

    /**
     * 视频加载进度百分比
     *
     * @param precent 加载进度百分比
     */
    private void onBufferingUpdate(int precent) {
    }

    /**
     * 阿里云播放器Seek完成
     */
    private void onSeekComplete() {
        resume();
    }

    /**
     * 视频准备结束的监听事件
     */
    private static class MyPrepareListener implements IAliyunVodPlayer.OnPreparedListener {

        private WeakReference<AliPlayerView> activityWeakReference;

        MyPrepareListener(AliPlayerView view) {
            activityWeakReference = new WeakReference<>(view);
        }

        @Override
        public void onPrepared() {//视频准备成功。失败则走OnErrorListener回调
            Logger.e("阿里云播放器准备成功");
            AliPlayerView view = activityWeakReference.get();
            if (view != null) {
                view.onPrepared();
            }
        }
    }

    /**
     * 首帧开始播放的监听事件
     */
    private static class MyFirstFrameListener implements IAliyunVodPlayer.OnFirstFrameStartListener {

        private WeakReference<AliPlayerView> activityWeakReference;

        MyFirstFrameListener(AliPlayerView view) {
            activityWeakReference = new WeakReference<>(view);
        }

        @Override
        public void onFirstFrameStart() {//首帧开始播放
            Logger.e("阿里云播放器开始播放首帧");
            AliPlayerView view = activityWeakReference.get();
            if (view != null) {
                view.onFirstFrameStart();
            }
        }
    }

    /**
     * 拖动结束监听事件
     */
    private static class MySeekCompleteListener implements IAliyunVodPlayer.OnSeekCompleteListener {

        private WeakReference<AliPlayerView> activityWeakReference;

        MySeekCompleteListener(AliPlayerView view) {
            activityWeakReference = new WeakReference<>(view);
        }

        @Override
        public void onSeekComplete() {// 拖动完成
            Logger.e("阿里云播放器Seek完成");
            AliPlayerView view = activityWeakReference.get();
            if (view != null) {
                view.onSeekComplete();
            }
        }
    }

    /**
     * 视频播放结束的监听事件
     */
    private static class MyCompletionListener implements IAliyunVodPlayer.OnCompletionListener {

        private WeakReference<AliPlayerView> activityWeakReference;

        MyCompletionListener(AliPlayerView view) {
            activityWeakReference = new WeakReference<>(view);
        }

        @Override
        public void onCompletion() {// 视频播放完成
            Logger.e("阿里云播放器播放完成");
            AliPlayerView view = activityWeakReference.get();
            if (view != null) {
                view.onCompletion();
            }
        }
    }

    /**
     * 频播放停止的监听事件
     */
    private static class MyStoppedListener implements IAliyunVodPlayer.OnStoppedListener {

        private WeakReference<AliPlayerView> activityWeakReference;

        MyStoppedListener(AliPlayerView view) {
            activityWeakReference = new WeakReference<>(view);
        }

        @Override
        public void onStopped() {// 视频播放停止
            Logger.e("阿里云播放器停止播放");
            AliPlayerView view = activityWeakReference.get();
            if (view != null) {
                view.onStopped();
            }
        }
    }

    /**
     * 视频缓冲状态的监听事件
     */
    private static class MyLoadingListener implements IAliyunVodPlayer.OnLoadingListener {

        private WeakReference<AliPlayerView> activityWeakReference;

        MyLoadingListener(AliPlayerView view) {
            activityWeakReference = new WeakReference<>(view);
        }

        @Override
        public void onLoadStart() {// 视频开始缓冲
            Logger.e("阿里云播放器开始缓冲");
            AliPlayerView view = activityWeakReference.get();
            if (view != null) {
                view.onLoadStart();
            }
        }

        @Override
        public void onLoadEnd() {// 视频缓冲结束
            Logger.e("阿里云播放器缓冲结束");
            AliPlayerView view = activityWeakReference.get();
            if (view != null) {
                view.onLoadEnd();
            }
        }

        @Override
        public void onLoadProgress(int precent) {// 视频缓冲进度百分比 precent:缓冲进度百分比
            Logger.e("阿里云播放器缓冲进度百分比:" + precent);
            AliPlayerView view = activityWeakReference.get();
            if (view != null) {
                Logger.e("阿里云播放器状态:" + view.getPlayerState().name());
                view.onLoadProgress(precent);
            }
        }
    }

    /**
     * 视频整体缓冲进度的监听事件
     */
    private static class MyBufferingUpdateListener implements IAliyunVodPlayer.OnBufferingUpdateListener {

        private WeakReference<AliPlayerView> activityWeakReference;

        MyBufferingUpdateListener(AliPlayerView view) {
            activityWeakReference = new WeakReference<>(view);
        }

        @Override
        public void onBufferingUpdate(int precent) {// 视频加载进度百分比 precent:加载进度百分比
            Logger.e("阿里云播放器加载进度百分比:" + precent);
            AliPlayerView view = activityWeakReference.get();
            if (view != null) {
                view.onBufferingUpdate(precent);
            }
        }
    }

    /**
     * 阿里云播放器播放错误
     */
    private static class MyErrorListener implements IAliyunVodPlayer.OnErrorListener {

        private WeakReference<AliPlayerView> activityWeakReference;

        MyErrorListener(AliPlayerView view) {
            activityWeakReference = new WeakReference<>(view);
        }

        @Override
        public void onError(int causeCode, int sceneCode, String message) {
            AliPlayerView view = activityWeakReference.get();
            if (view != null) {
                view.onError(causeCode, sceneCode, message);
            }
        }
    }

    /**
     * 视频信息的监听事件
     */
    private static class MyInfoListener implements IAliyunVodPlayer.OnInfoListener {

        @Override
        public void onInfo(int sceneType, int sceneCode) {// 播放器信息
            Logger.e("阿里云播放器播放器信息 SceneType：" + sceneType + " SceneCode" + sceneCode);
            // sceneType 场景类型
            // sceneCode 场景的值
            // sceneType值名称	sceneCode值	说明
            // MEDIA_INFO_BUFFERING_START	0	视频缓冲开始
            // MEDIA_INFO_BUFFERING_PROGRESS	视频的缓冲百分比	视频缓冲进度
            // MEDIA_INFO_BUFFERING_END	0	视频缓冲结束
            // MEDIA_INFO_VIDEO_RENDERING_START	0	视频首帧开始播放
        }
    }

    /**
     * 视频大小改变监听事件
     */
    private static class MyVideoSizeChangedListener implements IAliyunVodPlayer.OnVideoSizeChangedListener {

        @Override
        public void onVideoSizeChanged(int width, int height) {// 视频画面变化 width:视频的宽 height:视频的高
            Logger.e("阿里云播放器视频画面变化 width:" + width + " height" + height);
        }
    }

    /**
     * 阿里云播放器切换画质
     */
    private static class MyChangeQualityListener implements IAliyunVodPlayer.OnChangeQualityListener {

        @Override
        public void onChangeQualitySuccess(String finalQuality) {// 切换清晰度成功 finalQuality:最终切换的清晰度值
            Logger.d("阿里云播放器切换清晰度成功 FinalQuality:" + finalQuality);
        }

        @Override
        public void onChangeQualityFail(int code, String msg) {// 切换清晰度失败 code:错误码 msg:错误信息
            Logger.d("阿里云播放器切换清晰度失败 code:" + code + " msg:" + msg);
        }
    }

    /**
     * 视频重播的监听事件
     */
    private static class MyRePlayListener implements IAliyunVodPlayer.OnRePlayListener {

        @Override
        public void onReplaySuccess() {// 播放器重播成功
            Logger.d("阿里云播放器重播成功");
        }
    }

    /**
     * 阿里云播放器开始循环播放
     */
    private static class MyCircleStartListener implements IAliyunVodPlayer.OnCircleStartListener {

        @Override
        public void onCircleStart() {// 播放器循环播放开始
            Logger.d("阿里云播放器开始循环播放");
        }
    }

    /**
     * 视频自动播放的监听事件
     */
    private static class MyAutoPlayListener implements IAliyunVodPlayer.OnAutoPlayListener {

        @Override
        public void onAutoPlayStarted() {// 播放器自动播放开始
            Logger.d("阿里云播放器自动播放开始");
        }
    }

//    //开始播放
//        aliyunVodPlayer.start();
//    //停止播放，在开始播放之后调用
//        aliyunVodPlayer.stop();
//    //暂停播放
//        aliyunVodPlayer.pause();
//    //恢复播放，在调用暂停播放之后调用
//        aliyunVodPlayer.start();
//    //重播，播放上一次的url
//        aliyunVodPlayer.replay();
//    //Seek，跳转到指定时间点的视频画面，时间单位为秒
//        aliyunVodPlayer.seekTo(position);
//    //循环播放
//        aliyunVodPlayer.setCirclePlay(true);
//    //设置清晰度为标清
//        aliyunVodPlayer.changeQuality(IAliyunVodPlayer.QualityValue.QUALITY_LOW);
//    //获取播放的当前时间，单位为秒
//        aliyunVodPlayer.getCurrentPosition();
//    //获取视频的总时长，单位为秒
//        aliyunVodPlayer.getDuration();
//    //倍数播放支持0.5~2倍的设置，支持音频变速不变调
//        aliyunVodPlayer.setPlaySpeed(1F);
//
//    //设置缓存目录路径。在创建播放器类,并在调用prepare方法之前设置。
//    String sdDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/test_save_cache";
//        aliyunVodPlayer.setPlayingCache(true, sdDir, 60 * 60 /*单个文件的最大时长, s */, 300 /*缓存目录文件的总大小，MB*/);
//    //比如：maxSize设置500M时缓存文件超过500M后会优先覆盖最早缓存的文件。maxDuration设置为300秒时表示超过300秒的视频不会启用缓存功能。
//    //截图后获取图片数据，存储、上传或分享需用户自行处理
//    Bitmap bitmap = aliyunVodPlayer.snapShot();
//    // 获取播放器状态
//        aliyunVodPlayer.getPlayerState();
//    // 视频渲染旋转角度
//        aliyunVodPlayer.setRenderRotate(MediaPlayer.VideoRotate.ROTATE_90);
//    // 画面镜像
//        aliyunVodPlayer.setRenderMirrorMode(MediaPlayer.VideoMirrorMode.VIDEO_MIRROR_MODE_VERTICAL);
//    //设置自动播放，设置后调用prepare之后会自动开始播放，无需调start接口
//        aliyunVodPlayer.setAutoPlay(bAutoPlay);
//    //设置播放器音量（系统音量），值为0~100
//        aliyunVodPlayer.setVolume(volume);
//    //设置为静音
//        aliyunVodPlayer.setMuteMode(bMute);
//    //设置亮度（系统亮度），值为0~100
//        aliyunVodPlayer.setScreenBrightness(brightness);
//    //设置显示模式，可设置为fit方式填充或corp方式裁剪充满
//        aliyunVodPlayer.setVideoScalingMode(IAliyunVodPlayer.VideoScalingMode.VIDEO_SCALING_MODE_SCALE_TO_FIT);
//        aliyunVodPlayer.setVideoScalingMode(IAliyunVodPlayer.VideoScalingMode.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
//    //获取媒体信息,在prepareDone的时候才可以获取，主要可获取信息有视频ID、视频标题、视频封面、视频总时长、当前视频清晰度、所有视频清晰度
//        aliyunVodPlayer.getMediaInfo();

//    private int screenWidth;
//    private int screenCenterLine;
//    private float touchX;
//    private float touchY;
//    rsvPlayer.setOnTouchListener(new OnTouchListener() {
//        @Override
//        public boolean onTouch(View view, MotionEvent motionEvent) {
//            switch (motionEvent.getAction()) {
//                case MotionEvent.ACTION_DOWN:
//                    touchX = motionEvent.getRawX();
//                    touchY = motionEvent.getRawY();
//                    break;
//                case MotionEvent.ACTION_MOVE:
//                    float moveX = motionEvent.getRawX();
//                    float moveY = motionEvent.getRawY();
//                    float diffX = moveX - touchX;
//                    if (diffX < 10 && diffX > -10 && ((screenCenterLine > moveX && screenCenterLine > touchX) || (screenCenterLine < moveX && screenCenterLine < touchX))) {
//                        float diffY = moveY - touchY;
//                        if (diffY > 10 || diffY < -10) {
//                            int diff = (int) diffY / 10;
//                            if (screenCenterLine > moveX) {
//                                //TODO 亮度
//                                int brightness = aliyunVodPlayer.getScreenBrightness();
//                                aliyunVodPlayer.setScreenBrightness(brightness + diff);
//                                Logger.e("aliyunVodPlayer setScreenBrightness:" + aliyunVodPlayer.getScreenBrightness());
//                            } else {
//                                //TODO 声音
//                                int volume = aliyunVodPlayer.getVolume();
//                                aliyunVodPlayer.setVolume(volume + diff);
//                                Logger.e("aliyunVodPlayer setVolume:" + aliyunVodPlayer.getVolume());
//                            }
//                            touchX = moveX;
//                            touchY = moveY;
//                        }
//                    }
//                    break;
//            }
//            return false;
//        }
//    });

}
